package cn.szzsi._web;


import cn.szzsi.common.bean.CartItemCookie;
import cn.szzsi.common.bean.SystemConfig;
import cn.szzsi.common.bean.dto.Msg;
import cn.szzsi.common.kit.*;
import cn.szzsi.common.model.*;
import cn.szzsi.common.sms.SmsEmayUtil;
import cn.szzsi.common.sms.SmsZhuanxinUtil;
import cn.szzsi.interceptor.CommonInterceptor;
import cn.szzsi.service.MailService;
import cn.szzsi.service.UserBalanceDetailService;
import cn.szzsi.service.UserBalanceService;
import cn.szzsi.validator.MemberValidator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台类 - 用户(商户的会员)
 * Created by haotian on 2016/10/13.
 */
public class CustomerController extends BaseWebController<Member> {
    private Member member;
    private String uid;//商户id,也是用户的店铺id
    private String shopId;//店铺id
    private String path;//模板路径
    private Boolean isAgreeAgreement;//是否同意注册协议
    private String passwordRecoverKey;
    public static final String STATUS = "status";
    public static final String WARN = "warn";
    public static final String SUCCESS = "success";
    public static final String ERROR = "error";
    public static final String MESSAGE = "message";

    /**
     * wap端登陆界面
     */
    @Clear
    @Before(CommonInterceptor.class)
    public void wapLogin(){
        String shopId=getPara("shopId");
        getTemplatePath(shopId,"login");
    }

    /**
     * wap端注册界面
     */
    @Clear
    @Before(CommonInterceptor.class)
    public void wapRegisterForm(){
        String shopId=getPara("shopId");
        String code=getPara(0);
        setAttr("code",code);
        getTemplatePath(shopId,"register");
    }

    /**
     * wap端注册用户
     */
    @Clear
    @Before({CommonInterceptor.class,Tx.class})
    public void wapRegisterIn(){
        member = getModel(Member.class);
        String phoneCaptcha=getPara("phoneCaptcha");
        String code=getPara("code");//上级推荐码
        if(Member.dao.getByPhone(member.getPhone())!=null){
            renderJson(Ret.fail("info","手机还已存在!"));
            return;
        }
        if(CacheKit.get("sms",member.getPhone())==null){
            renderJson(Ret.fail("info","手机验证码已过期,请重新获取!"));
            return;
        }
        if(!phoneCaptcha.equals(CacheKit.get("sms",member.getPhone()).toString())){
            renderJson(Ret.fail("info","手机验证码不正确!"));
            return;
        }
        if(Member.dao.isExistByCustomerUsername(getPara("member.username"),shopId)){
            renderJson(Ret.fail("info","用户名已存在"));
            return;
        }

        //查看上级
        String pid="0";
        String pids="0";
        if (StrKit.notBlank(code)){
            Member pidMember=Member.dao.getByCode(code);
            if(pidMember!=null){
                pid=pidMember.getId();
                pids=pidMember.getPids();
                if (!"0".equals(pids)){
                    pids=pids+","+pid;
                }else{
                    pids=pid;
                }
            }
        }
        //查看上级
        member.set("username", member.getUsername().toLowerCase());
        member.set("password", DigestUtils.md5Hex(member.getStr("password")));
        member.set("shopId",CommonUtil.PLATFROM_FLAG);
        member.set("safeQuestion", null);
        member.set("safeAnswer", null);
        member.set("memberRankId", null);
        member.set("point", 0);
        member.set("deposit", new BigDecimal("0"));
        member.set("isAccountEnabled", true);
        member.set("isAccountLocked", false);
        member.set("loginFailureCount", 0);
        member.set("passwordRecoverKey", null);
        member.set("lockedDate", null);
        member.set("loginDate", new Date());
        member.set("registerIp",getRequest().getRemoteAddr());
        member.set("loginIp",getRequest().getRemoteAddr());
        member.set("id", CommonUtil.getUUID());
        member.setPid(pid);
        member.setPids(pids);
        member.set("createDate", new Date());
        member.set("code", IdGen.get().nextId(10));
        member.save();

        //SiteConfig siteConfig= SiteConfig.dao.findByShopId(shopId);
        //会员首次注册根据商户设置的余额赠送
        //UserBalanceService.service.saveInfo(member,new BigDecimal(siteConfig.getFirstRegisterMoney()),0,new BigDecimal(0));
        //如果赠送金额大于0,增加流水明细
        //if(siteConfig.getFirstRegisterMoney()>0){
            //UserBalanceDetailService.service.saveRegisterMoney(member.getId(),new BigDecimal(siteConfig.getFirstRegisterMoney()), UserBalanceDetail.BalanceType.other.ordinal(),shopId);
        //}

        // 写入会员登录Session
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getStr("id"));

        // 写入会员登录Cookie
        Cookie loginMemberCookie = null;
        Cookie loginTypeCookie = null;
        try {
            loginMemberCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(member.getStr("username").toLowerCase(), "UTF-8"));
            loginTypeCookie=new Cookie(Member.LOGIN_TYPE_COOKIE_NAME,"customer");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        loginMemberCookie.setPath(getRequest().getContextPath() + "/");
        loginTypeCookie.setPath(getRequest().getContextPath()+"/");
        getResponse().addCookie(loginMemberCookie);
        getResponse().addCookie(loginTypeCookie);

        // 合并购物车
        Cookie[] cookies = getRequest().getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
                    if (StringUtils.isNotEmpty(cookie.getValue())) {
                        JSONArray jsonArray = null;
                        try {
                            jsonArray = JSON.parseArray(URLDecoder.decode(cookie.getValue(),"UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        List<CartItemCookie> cartItemCookieList = JSON.parseArray(jsonArray.toJSONString(), CartItemCookie.class);
                        for (CartItemCookie cartItemCookie : cartItemCookieList) {
                            Product product = Product.dao.findById(cartItemCookie.getI());
                            if (product != null) {
                                CartItem cartItem = new CartItem();
                                cartItem.set("member_id",member.getStr("id"));
                                cartItem.set("product_id",product.getStr("id"));
                                cartItem.set("quantity",cartItemCookie.getQ());
                                cartItem.save(cartItem);
                            }
                        }
                    }
                }
            }
        }
        // 清空临时购物车Cookie
        Cookie cartItemCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
        cartItemCookie.setPath(getRequest().getContextPath() + "/");
        cartItemCookie.setMaxAge(0);
        getResponse().addCookie(cartItemCookie);

        renderJson(Ret.ok("info","恭喜您注册成功"));

    }

    /**
     * 获取手机验证码,并校验用户是知否存在
     */
    @Clear
    public void getCaptcha(){
        String phone =getPara("phone");
        if(StrKit.isBlank(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }
        /*if(StrKit.notBlank(phone)&&!RegexUtils.checkMobile(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }*/
        Member member= Member.dao.getByPhone(phone);
        if(member!=null){
            renderJson(Ret.fail("info","该手机号已注册,请换个试试!"));
            return;
        }
        //同一个手机号限制一分钟之内只能发送一条
        Long lastTimeMillis = CacheKit.get("sms_last_time",phone);
        if(lastTimeMillis!=null){
            Long currentTimeMillis=System.currentTimeMillis();
            if((currentTimeMillis-lastTimeMillis)<60000){
                renderJson(Ret.fail("info","您的操作过于频繁,请稍后再试!!"));
                return;
            }

        }
        //同一个手机号限制一分钟之内只能发送一条
        //【微米荟商城】您的验证码:686260 ，请勿泄露！感谢您的使用！
        String captcha = CommonUtil.getSixRandom();//六位纯数字验证码
        String message = "【微米荟商城】您的验证码:"+captcha+" ，请勿泄露！感谢您的使用！";
        boolean sendResult= SmsEmayUtil.sendToSms("0",phone,message,"yzm","wmh",captcha);
        if(sendResult){
            renderJson(Ret.ok("info","发送成功!"));
        }else{
            renderJson(Ret.fail("info","发送失败!"));
        }
    }



    @Clear
    @Before(CommonInterceptor.class)
    public void login() {
        //shopId=getPara("shopId");
        String phone = getPara("member.phone","");
        String password = getPara("member.password","");
        Member loginMember = Member.dao.verifyCustomerByUsernameOrPhone(phone,password);
        if(loginMember==null){
            renderJson(Ret.fail("info","登录名或密码错误!"));
            return;
        }

        loginMember.set("loginIp", getRequest().getRemoteAddr());
        loginMember.set("loginDate", new Date());
        loginMember.update();

        // 写入会员登录Session
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, loginMember.getStr("id"));

        // 合并购物车
        Cookie[] cookies = getRequest().getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
                    if (StringUtils.isNotEmpty(cookie.getValue())) {
                        JSONArray jsonArray = null;
                        try {
                            jsonArray = JSON.parseArray(URLDecoder.decode(cookie.getValue(),"UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        List<CartItemCookie> cartItemCookieList = JSON.parseArray(jsonArray.toJSONString(), CartItemCookie.class);
                        for (CartItemCookie cartItemCookie : cartItemCookieList) {
                            Product product = Product.dao.findById(cartItemCookie.getI());
                            if (product != null) {
                                CartItem cartItem = new CartItem();
                                cartItem.set("member_id",loginMember.getStr("id"));
                                cartItem.set("product_id",product.getStr("id"));
                                cartItem.set("quantity",cartItemCookie.getQ());
                                cartItem.save(cartItem);
                            }
                        }
                    }
                }
            }
        }

        // 清空临时购物车Cookie
        Cookie cartItemCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
        cartItemCookie.setPath(getRequest().getContextPath() + "/");
        cartItemCookie.setMaxAge(0);
        getResponse().addCookie(cartItemCookie);

        String redirectionUrl = getSessionAttr(Member.LOGIN_REDIRECTION_URL_SESSION_NAME);
        getRequest().getSession().removeAttribute(Member.LOGIN_REDIRECTION_URL_SESSION_NAME);
        path= CommonUtil.getPathByUidAndType(shopId, CommonUtil.isMobileDevice(getRequest()));//获取模板路径
        if (StringUtils.isEmpty(redirectionUrl)) {
            renderJson(Ret.ok().set("url","/b/customerCenter"));
        } else {
            renderJson(Ret.ok().set("url",redirectionUrl));
        }
    }

    @Clear
    @Before(Tx.class)
    public void ajaxLogin() {
        String username = getPara("member.username","");
        String password = getPara("member.password","");
        String captchaToken = getPara("captchaToken","");
        shopId=getPara("shopId");
        SystemConfig systemConfig = getSystemConfig();
        Member loginMember = Member.dao.getCustomerByUsernameAndShopId(username,shopId);
        if (loginMember != null) {
            // 解除会员账户锁定
            if (loginMember.getBoolean("isAccountLocked")) {
                if (systemConfig.getIsLoginFailureLock()) {
                    int loginFailureLockTime = systemConfig.getLoginFailureLockTime();
                    if (loginFailureLockTime != 0) {
                        Date lockedDate = loginMember.getDate("lockedDate");
                        Date nonLockedTime = DateUtils.addMinutes(lockedDate, loginFailureLockTime);
                        Date now = new Date();
                        if (now.after(nonLockedTime)) {
                            loginMember.set("loginFailureCount", 0);
                            loginMember.set("isAccountLocked",false);
                            loginMember.set("lockedDate",null);
                            loginMember.update();
                        }
                    }
                } else {
                    loginMember.set("loginFailureCount", 0);
                    loginMember.set("isAccountLocked",false);
                    loginMember.set("lockedDate",null);
                    loginMember.update();
                }
            }
            if (!loginMember.getBoolean("isAccountEnabled")) {
                renderJson(Msg.fail("您的账号已被禁用,无法登录！",""));
                return;
            }
            if (loginMember.getBoolean("isAccountLocked")) {
                renderJson(Msg.fail("您的账号已被锁定,无法登录！",""));
                return;
            }
            if (!Member.dao.verifyCustomer(username, password,shopId)) {
                if (systemConfig.getIsLoginFailureLock()) {
                    int loginFailureLockCount = getSystemConfig().getLoginFailureLockCount();//5
                    int loginFailureCount = loginMember.getInt("loginFailureCount") + 1;//密码输入错误,登录错误次数加1
                    if (loginFailureCount >= systemConfig.getLoginFailureLockCount()) {
                        loginMember.set("isAccountLocked",true);//同一账号允许连续登录失败的最大次数，超出次数后将锁定其账号
                        loginMember.set("lockedDate",new Date());
                    }
                    loginMember.set("loginFailureCount",loginFailureCount);
                    loginMember.update();
                    if (loginFailureLockCount - loginFailureCount <= 3) {
                        renderJson(Msg.fail("若连续" + loginFailureLockCount + "次密码输入错误,账号将被锁定,还有" + (loginFailureLockCount - loginMember.getInt("loginFailureCount")) + " 次机会。",""));
                        return;
                    } else {
                        renderJson(Msg.fail("您的用户名或密码错误！",""));
                        return;
                    }
                } else {
                    renderJson(Msg.fail("您的用户名或密码错误！",""));
                    //ajaxJsonErrorMessage("您的用户名或密码错误！");
                    return;
                }
            }
        } else {
            //System.out.println("**************会员不存在");
            renderJson(Msg.fail("您的用户名或密码错误！",""));
            //ajaxJsonErrorMessage("您的用户名或密码错误！");
            return;
        }
        loginMember.set("loginIp",getRequest().getRemoteAddr());
        loginMember.set("loginDate",new Date());
        loginMember.update();

        // 写入会员登录Session
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, loginMember.getStr("id"));

        // 写入会员登录Cookie和登录类型Cookie
        Cookie loginMemberUsernameCookie = null;
        Cookie loginTypeCookie = null;
        try {
            loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(username.toLowerCase(), "UTF-8"));
            loginTypeCookie=new Cookie(Member.LOGIN_TYPE_COOKIE_NAME,"customer");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        loginMemberUsernameCookie.setPath(getRequest().getContextPath() + "/");
        loginTypeCookie.setPath(getRequest().getContextPath()+"/");
        getResponse().addCookie(loginMemberUsernameCookie);
        getResponse().addCookie(loginTypeCookie);

        // 合并购物车
        Cookie[] cookies = getRequest().getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
                    if (StringUtils.isNotEmpty(cookie.getValue())) {
                        JSONArray jsonArray = null;
                        try {
                            jsonArray = JSON.parseArray(URLDecoder.decode(cookie.getValue(),"UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        List<CartItemCookie> cartItemCookieList = JSON.parseArray(jsonArray.toJSONString(), CartItemCookie.class);
                        for (CartItemCookie cartItemCookie : cartItemCookieList) {
                            Product product = Product.dao.findById(cartItemCookie.getI());
                            if (product != null) {
                                CartItem cartItem = new CartItem();
                                cartItem.set("member_id",loginMember.getStr("id"));
                                cartItem.set("product_id",product.getStr("id"));
                                cartItem.set("quantity",cartItemCookie.getQ());
                                cartItem.save(cartItem);
                            }
                        }
                    }
                }
            }
        }

        // 清空临时购物车Cookie
        Cookie cartItemCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
        cartItemCookie.setPath(getRequest().getContextPath() + "/");
        cartItemCookie.setMaxAge(0);
        getResponse().addCookie(cartItemCookie);
        renderJson(Msg.SUCCESS);
        //ajaxJsonSuccessMessage("会员登录成功!");

    }

    // 获取注册协议内容
    public void agreement() {
        renderJson(Agreement.dao.getAll().getStr("content"));
    }

    // Ajax会员注册保存
    @Clear
    @Before(Tx.class)
    public void ajaxRegister() {
        isAgreeAgreement = getParaToBoolean("isAgreeAgreement");
        member = getModel(Member.class);
        shopId=getPara("shopId");
        if (Member.dao.isExistByCustomerUsername(member.getStr("username"),shopId)) {
            System.out.println("**************用户名已存在");
            renderJson(Msg.fail("用户名已存在",""));
            return;
        }
        member.set("username", member.getStr("username").toLowerCase());
        member.set("password", DigestUtils.md5Hex(member.getStr("password")));
        member.set("shopId",shopId);
        member.set("safeQuestion", null);
        member.set("safeAnswer", null);
        member.set("memberRankId", MemberRank.dao.getDefaultMemberRank(shopId).getStr("id"));
        member.set("point", 0);
        member.set("deposit", new BigDecimal("0"));
        member.set("isAccountEnabled", true);
        member.set("isAccountLocked", false);
        member.set("loginFailureCount", 0);
        member.set("passwordRecoverKey", null);
        member.set("lockedDate", null);
        member.set("loginDate", new Date());
        member.set("registerIp",getRequest().getRemoteAddr());
        member.set("loginIp",getRequest().getRemoteAddr());
        member.set("id", CommonUtil.getUUID());
        member.set("createDate", new Date());
        member.save();

        // 写入会员登录Session
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getStr("id"));

        // 写入会员登录Cookie
        Cookie loginMemberCookie = null;
        Cookie loginTypeCookie = null;
        try {
            loginMemberCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(member.getStr("username").toLowerCase(), "UTF-8"));
            loginTypeCookie=new Cookie(Member.LOGIN_TYPE_COOKIE_NAME,"customer");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        loginMemberCookie.setPath(getRequest().getContextPath() + "/");
        loginTypeCookie.setPath(getRequest().getContextPath()+"/");
        getResponse().addCookie(loginMemberCookie);
        getResponse().addCookie(loginTypeCookie);

        // 合并购物车
        Cookie[] cookies = getRequest().getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
                    if (StringUtils.isNotEmpty(cookie.getValue())) {
                        JSONArray jsonArray = null;
                        try {
                            jsonArray = JSON.parseArray(URLDecoder.decode(cookie.getValue(),"UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        List<CartItemCookie> cartItemCookieList = JSON.parseArray(jsonArray.toJSONString(), CartItemCookie.class);
                        for (CartItemCookie cartItemCookie : cartItemCookieList) {
                            Product product = Product.dao.findById(cartItemCookie.getI());
                            if (product != null) {
                                CartItem cartItem = new CartItem();
                                cartItem.set("member_id",member.getStr("id"));
                                cartItem.set("product_id",product.getStr("id"));
                                cartItem.set("quantity",cartItemCookie.getQ());
                                cartItem.save(cartItem);
                            }
                        }
                    }
                }
            }
        }

        // 清空临时购物车Cookie
        Cookie cartItemCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
        cartItemCookie.setPath(getRequest().getContextPath() + "/");
        cartItemCookie.setMaxAge(0);
        getResponse().addCookie(cartItemCookie);
        renderJson(Msg.SUCCESS);
    }

    // 密码找回
    public void passwordRecover() {
        uid=getPara("shopId");
        getTemplatePath(uid,"member_password_recover");

    }

    // 发送密码找回邮件
    @Before(MemberValidator.class)
    public void sendPasswordRecoverMail() {
        member = getModel(Member.class);
        Member persistent = Member.dao.getCustomerByUsername(member.getStr("username"));
        if (persistent == null || StringUtils.equalsIgnoreCase(persistent.getStr("email"), member.getStr("email")) == false) {
            ajaxJsonErrorMessage("用户名或E-mail输入错误！");
            return;
        }
        if (!MailService.service.isMailConfigComplete()) {
            ajaxJsonErrorMessage("系统邮件发送功能尚未配置，请联系管理员！");
            return;
        }
        if (StringUtils.isNotEmpty(persistent.getStr("safeQuestion")) && StringUtils.isNotEmpty(persistent.getStr("safeQuestion"))) {
            if (StringUtils.isEmpty(member.getStr("safeAnswer"))) {
                Map<String, String> jsonMap = new HashMap<String, String>();
                jsonMap.put("safeQuestion", persistent.getStr("safeQuestion"));
                jsonMap.put(STATUS, WARN);
                jsonMap.put(MESSAGE, "请填写密码保护问题答案！");
                renderJson(jsonMap);
                return;
            }
            if (StringUtils.equalsIgnoreCase(persistent.getStr("safeAnswer"), member.getStr("safeAnswer")) == false) {
                ajaxJsonErrorMessage("密码保护答案错误！");
                return;
            }
        }
        persistent.set("passwordRecoverKey", Member.dao.buildPasswordRecoverKey());
        persistent.set("modifyDate", new Date());
        persistent.update();

        if (MailService.service.sendPasswordRecoverMail(persistent)) {
            ajaxJsonSuccessMessage("系统已发送邮件到您的E-mail，请根据邮件提示操作！");
        } else {
            ajaxJsonErrorMessage("发送失败,请联系管理员！");
        }
    }

    // 密码修改
    public void passwordModify() {
        String id = getPara("id","");
        passwordRecoverKey = getPara("passwordRecoverKey","");

        Member persistent = Member.dao.findById(id);
        if (persistent == null || StringUtils.equalsIgnoreCase(persistent.getStr("passwordRecoverKey"), passwordRecoverKey) == false) {
            addActionError("对不起，此密码找回链接已失效！");
            return;
        }
        Date passwordRecoverKeyBuildDate = Member.dao.getPasswordRecoverKeyBuildDate(passwordRecoverKey);
        Date passwordRecoverKeyExpiredDate = DateUtils.addMinutes(passwordRecoverKeyBuildDate, Member.PASSWORD_RECOVER_KEY_PERIOD);
        Date now = new Date();
        if (now.after(passwordRecoverKeyExpiredDate)) {
            addActionError("对不起，此密码找回链接已过期！");
            return;
        }
        setAttr("member", persistent);
        render(CommonUtil.TEMPLATE_PATH+"/shop/member_password_modify.html");
    }

    // 密码更新
    @Before(MemberValidator.class)
    public void passwordUpdate() {
        member = getModel(Member.class);
        passwordRecoverKey =member.getStr("passwordRecoverKey");

        Member persistent = Member.dao.findById(member.getStr("id"));
        if (persistent == null || StringUtils.equalsIgnoreCase(persistent.getStr("passwordRecoverKey"), passwordRecoverKey) == false) {
            addActionError("对不起，此密码找回链接已失效！");
            return;
        }
        Date passwordRecoverKeyBuildDate = Member.dao.getPasswordRecoverKeyBuildDate(passwordRecoverKey);
        Date passwordRecoverKeyExpiredDate = DateUtils.addMinutes(passwordRecoverKeyBuildDate, Member.PASSWORD_RECOVER_KEY_PERIOD);
        Date now = new Date();
        if (now.after(passwordRecoverKeyExpiredDate)) {
            addActionError("对不起，此密码找回链接已过期！");
            return;
        }
        persistent.set("password", DigestUtils.md5Hex(member.getStr("password")));
        persistent.set("passwordRecoverKey", null);
        persistent.set("modifyDate", new Date());
        persistent.update();
        renderSuccessMessage("密码修改成功！", "/html/login.html");
    }

    // 检查用户名是否存在
    public void checkUsername() {
        String username = getPara("member.username","");
        shopId=getPara("shopId");
        if (Member.dao.isExistByCustomerUsername(username,shopId)) {
            System.out.println("**************用户名已存在");
            renderText("false");
        } else {
            System.out.println("**************用户名不存在");
            renderText("true");
        }
    }

    public void addActionError(String error){
        setAttr("errorMessages", error);
        redirect("/common/error.html");
        render(CommonUtil.TEMPLATE_PATH+"/common/error.html");
    }
    @Clear
    public void renderErrorMessage(String message) {
        setAttr("errorMessages", message);
        setAttr("systemConfig", SystemConfigUtil.getSystemConfig());
        setAttr("base", getRequest().getContextPath());
        render(CommonUtil.TEMPLATE_PATH+"/admin/error.html");
    }

    // 获取系统配置信息
    public SystemConfig getSystemConfig() {
        return SystemConfigUtil.getSystemConfig();
    }

    // 输出JSON错误消息，返回null
    public void ajaxJsonErrorMessage(String message) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, ERROR);
        jsonMap.put(MESSAGE, message);
        renderJson(jsonMap);
    }

    // 输出JSON成功消息，返回null
    public void ajaxJsonSuccessMessage(String message) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, SUCCESS);
        jsonMap.put(MESSAGE, message);
        renderJson(jsonMap);
    }

    public void renderSuccessMessage(String message, String url){
        setAttr(MESSAGE, message);
        setAttr("redirectionUrl", url);
        render(CommonUtil.TEMPLATE_PATH+"/shop/success.html");
    }
}
